package com.ruoyi.message.notice;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.function.domain.ChatRecord;
import com.ruoyi.function.service.IChatRecordService;

import com.ruoyi.message.notice.vo.NoticeVO;
import com.ruoyi.message.utils.CommonUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;

/**
 * WebSocket消息处理器（集成MyBatis）
 */
@Component
public class NoticeWebSocketHandler extends TextWebSocketHandler {


    @Autowired
    private IChatRecordService chatRecordService;

    // Key: 用户ID, Value: WebSocketSession
    private static ConcurrentHashMap<String, WebSocketSession> noticeSessions = new ConcurrentHashMap<>();

    public static void addSession(String userId, WebSocketSession session) {
        noticeSessions.put(userId, session);
    }

    public static WebSocketSession getSession(String userId) {
        return noticeSessions.get(userId);
    }

    public static void removeSession(String userId) {
        noticeSessions.remove(userId);
    }

    /**
     * 连接完成之后
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        Map<String, Object> attributes = session.getAttributes();
        Long receiverId = null;
        if (Objects.nonNull(attributes.get("receiverId"))) {
            receiverId = (Long) attributes.get("receiverId");
            // 获取随机5位数
            String sessionKey = "_" + receiverId + "_" + CommonUtil.getRandomString(5);
            addSession(sessionKey, session);
        }
        // 推送历史消息
        List<NoticeVO> history = null;
        //List<NoticeVO> history = chatService.getHistory(senderId, receiverId);
        /*if (CollectionUtils.isEmpty(history)) {
            history = new ArrayList<>();
            NoticeVO chatMessage = new NoticeVO(null, "您好，请问有什么可以帮您？", false, new Date(), senderId);
            // 保存到数据库
            chatService.saveMessage(chatMessage.getContent(), chatMessage.getUserFlag(), chatMessage.getUserId());
            history.add(chatMessage);
        }*/
        if (CollectionUtils.isNotEmpty(history)) {
            //history = history.stream().sorted(Comparator.comparing(NoticeVO::getCreateTime)).collect(Collectors.toList());
            session.sendMessage(new TextMessage(JSON.toJSONString(history)));
        }
    }

    /**
     * 接收到消息
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        NoticeVO msg = JSON.parseObject(message.getPayload(), NoticeVO.class);
        if (Objects.nonNull(msg) && msg.getSenderId() != null && msg.getReceiverId() != null) {
            // 保存到数据库
            ChatRecord chatRecord = new ChatRecord();
            BeanUtils.copyProperties(msg,chatRecord );
            chatRecordService.insertChatRecord(chatRecord);
//            chatService.saveMessage(msg.getContent(), msg.getUserFlag(), msg.getUserId());
            // 广播消息
            broadcastMessage(msg);
        }
    }

    /**
     * 关闭连接之后
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        AtomicReference<String> key = new AtomicReference<>();
        noticeSessions.forEach((k, v) -> {
            if (v == session) {
                key.set(k);
            }
        });
        if (StringUtils.isNotBlank(key.get())) {
            noticeSessions.remove(key.get());
        }
        System.out.println("noticeSessions size: " + noticeSessions.size());
        super.afterConnectionClosed(session, status);
    }

    /**
     * 发信息
     * 实际上就是广播给所有相关的WebSocketSession
     * @param msg
     */
    public static void broadcastMessage(NoticeVO msg) {
        Long receiverId = Long.parseLong(msg.getReceiverId());
        TextMessage textMessage = new TextMessage(JSON.toJSONString(msg));
        System.out.println("noticeSessions size: " + noticeSessions.size());
        // 遍历所有session 给同一个用户会话发消息
        noticeSessions.forEach((k, v) -> {
            if (k.contains("_" + receiverId.toString() + "_")) {
                try {
                    if (v.isOpen()) v.sendMessage(textMessage);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }
}